﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DBSchemaService.Utils;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System.Net.Mail;
using Microsoft.TeamFoundation.Server;
using System.IO;

namespace DBSchemaService.Core
{
    public class EmailProcessor
    {
        public List<EmailInfo> _email;


        public EmailProcessor(List<EmailInfo> email)
        {
            _email = email;
        }
        /// <summary>
        /// We need to process the emailinfo items here
        /// </summary>
        public void Start()
        {
            EmailInfo emailInfoForSchema;
            //schema change only
            if (_email.Count == 1)
            {
                emailInfoForSchema = _email.ElementAt(0);
                //check if schema or sproc
                if (emailInfoForSchema.IsStructure)
                    EmailHelper.NotifySpecifiedAddressSuccessfulSchema(emailInfoForSchema.EmailAddressToSendTo, emailInfoForSchema.EmailDisplayName, emailInfoForSchema.Wi, emailInfoForSchema.ServerPath, emailInfoForSchema.ChangeSetNumber);
                else
                    EmailHelper.NotifySpecifiedAddressSuccessfulSproc(emailInfoForSchema.EmailAddressToSendTo, emailInfoForSchema.EmailDisplayName, emailInfoForSchema.Database, emailInfoForSchema.ServerPath, emailInfoForSchema.ChangeSetNumber);
            }
            else if (_email.Count > 1) //sprocs changes
            {
                emailInfoForSchema = _email.ElementAt(0);              
                //check if first is schema or sproc
                if (emailInfoForSchema.IsStructure)
                    NotifySpecifiedAddressSuccessfulSchemaAndSproc(_email);
                else
                    NotifySpecifiedAddressSuccessfulSprocs(_email);
            }
        }

        private static void NotifySpecifiedAddressSuccessfulSchemaAndSproc(List<EmailInfo> emailInfo)
        {
            string databaseComparator = string.Empty;
            try
            {
                if (emailInfo == null)
                    throw new NullReferenceException("Method NotifySpecifiedAddressSuccessfulSchemaAndSproc: Parameter emailInfo is null");
            }
            catch (NullReferenceException ex)
            {
                using (StreamWriter sw = new StreamWriter(@"C:\Logs\schemaservice_log.txt", true))
                {
                    sw.WriteLine(ex.Message);
                    sw.WriteLine(ex.Source);
                    sw.WriteLine(ex.InnerException);
                    sw.WriteLine(ex.StackTrace);
                }
            }

            try
            {


                //sort the list to get database order, then move structure to first position                                
                emailInfo = emailInfo.OrderBy(i => i.Database).ThenByDescending(i=>i.IsStructure).ToList();
                EmailInfo emailInfoSchema = emailInfo.ElementAt(0);
                WorkItem wi = emailInfo.Where(i => i.IsStructure).FirstOrDefault().Wi;
                int changesetNumber = emailInfoSchema.ChangeSetNumber;
                MailMessage mail = new MailMessage();

                mail.To.Add(new MailAddress(emailInfoSchema.EmailAddressToSendTo, emailInfoSchema.EmailDisplayName));
                //set the content
                mail.Subject = string.Format("Database Changes");
                mail.Body = string.Format("Please get the latest from TFS and run the following files in your <b>{0} database</b>", emailInfoSchema.Database);
                
                //loop here through each item in the emailInfo list
                foreach (EmailInfo e in emailInfo)
                {
                    if (e.Database.ToLower() == databaseComparator || string.IsNullOrEmpty(databaseComparator))
                    {
                        mail.Body += "<br />";
                        mail.Body += "<br />";                        
                        mail.Body += string.Format(e.ServerPath);
                    }
                    else
                    {
                        mail.Body += "<br />";
                        mail.Body += "<br />";
                        mail.Body += "<br />";
                        mail.Body += string.Format("Please get the latest from TFS and run the following files in your <b>{0} database</b>", e.Database);
                        mail.Body += "<br />";
                        mail.Body += "<br />";
                        mail.Body += string.Format(e.ServerPath);
                    }
                    databaseComparator = e.Database.ToLower();
                }

                mail.Body += "<hr />";
                mail.Body += "<b>Schema Change Information:</b>";
                mail.Body += "<br />";
                mail.Body += wi.Fields["Info"].Value.ToString();                
                mail.Body += "<hr />";
                mail.Body += "<b>Schema Change Details:</b>";
                mail.Body += "<br />";
                mail.Body += string.Format("Schema Change Creator: {0}", wi.CreatedBy);
                mail.Body += "<br />";
                mail.Body += string.Format("Schema Change Work Item ID: {0}", wi.Id);
                mail.Body += "<br />";
                mail.Body += string.Format("Schema Change Work Item Title: {0}", wi.Title);
                mail.Body += "<br />";
                mail.Body += string.Format("Schema Change Work Item Area Path: {0}", wi.Fields["Area"].Value);
                mail.Body += "<br />";
                mail.Body += string.Format("Schema Change Work Item Iteration: {0}", wi.IterationPath);
                mail.Body += "<br />";
                mail.Body += string.Format("Schema Change Changeset #: {0}", changesetNumber);
                mail.IsBodyHtml = true;

                //send the message
                SmtpClient smtp = new SmtpClient();
                smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                smtp.Send(mail);
            }
            catch (Exception ex)
            {
                using (StreamWriter sw = new StreamWriter(@"C:\Logs\schemaservice_log.txt", true))
                {
                    sw.WriteLine(ex.Message);
                    sw.WriteLine(ex.Source);
                    sw.WriteLine(ex.InnerException);
                    sw.WriteLine(ex.StackTrace);
                }
            }
        }

        private static void NotifySpecifiedAddressSuccessfulSprocs(List<EmailInfo> emailInfo)
        {
            EmailInfo emailInfoSproc = emailInfo.ElementAt(0);
            try
            {
                if (emailInfoSproc.EmailAddressToSendTo == null)
                    throw new NullReferenceException("Method NotifySpecifiedAddressSuccessfulSprocs: Parameter emailAddress is null");
            }
            catch (NullReferenceException ex)
            {
                using (StreamWriter sw = new StreamWriter(@"C:\Logs\schemaservice_log.txt", true))
                {
                    sw.WriteLine(ex.Message);
                    sw.WriteLine(ex.Source);
                    sw.WriteLine(ex.InnerException);
                    sw.WriteLine(ex.StackTrace);
                }
            }

            try
            {
                MailMessage mail = new MailMessage();
                mail.To.Add(new MailAddress(emailInfoSproc.EmailAddressToSendTo, emailInfoSproc.EmailDisplayName));

                //set the content
                mail.Subject = string.Format("Database Changes");
                mail.Body = string.Format("Please get the latest from TFS and run the following file in your <b>{0} database</b>", emailInfoSproc.Database);               
                
                foreach (EmailInfo e in emailInfo)
                {
                    if (emailInfoSproc.Database != e.Database)
                    {
                        
                        mail.Body += "<br />";
                        mail.Body += "<br />";
                        mail.Body += "<br />";
                        mail.Body += string.Format("Please get the latest from TFS and run the following file in your <b>{0} database</b>", e.Database);
                        mail.Body += "<br />";
                        mail.Body += "<br />";
                        mail.Body += string.Format(e.ServerPath);
                    }
                    else
                    {
                        mail.Body += "<br />";
                        mail.Body += "<br />";
                        mail.Body += string.Format(e.ServerPath);
                        
                    }
                   
                }
                mail.Body += "<br />";
                mail.Body += "<hr />";
                mail.Body += "<b>Change Details:</b>";
                mail.Body += "<br />";

                foreach (EmailInfo e in emailInfo)
                {                    
                    mail.Body += string.Format("Changeset #: {0}", e.ChangeSetNumber);
                    mail.Body += "<br />";
                }
                mail.IsBodyHtml = true;

                //send the message
                SmtpClient smtp = new SmtpClient();
                smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                smtp.Send(mail);
            }
            catch (Exception ex)
            {
                using (StreamWriter sw = new StreamWriter(@"C:\Logs\schemaservice_log.txt", true))
                {
                    sw.WriteLine(ex.Message);
                    sw.WriteLine(ex.Source);
                    sw.WriteLine(ex.InnerException);
                    sw.WriteLine(ex.StackTrace);
                }
            }
        }





    }
}
